package com.yinp.proapp.module.im.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.yinp.proapp.R;
import com.yinp.proapp.activity.bean.MyUserInfo;
import com.yinp.proapp.base.activity.AppBaseActivity;
import com.yinp.proapp.bean.ChangFresh;
import com.yinp.proapp.databinding.ActivitySingleCharBinding;
import com.yinp.proapp.databinding.DialogShowImgBinding;
import com.yinp.proapp.module.im.ImConstant;
import com.yinp.proapp.module.im.adapter.ImMessageAdapter;
import com.yinp.proapp.module.im.bean.ConversationListBean;
import com.yinp.proapp.module.im.bean.ImMessageBean;
import com.yinp.proapp.utils.AppUtils;
import com.yinp.proapp.utils.GlideUtils;
import com.yinp.proapp.utils.MTextWatcher;
import com.yinp.proapp.utils.SoftHideKeyBoardUtil;
import com.yinp.proapp.utils.StatusBarUtil;
import com.yinp.tools.fragment_dialog.BaseDialogFragment;
import com.yinp.tools.fragment_dialog.CommonDialogFragment;
import com.yinp.tools.fragment_dialog.DialogFragmentHolder;
import com.yinp.tools.fragment_dialog.ViewConvertListener;

import org.greenrobot.eventbus.EventBus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

/**
 * @Author: yinp
 * @Date: 2021/11/26
 * @Description:单人实时3聊天
 */
public class SingleCharActivity extends AppBaseActivity<ActivitySingleCharBinding> {
    private ImMessageAdapter messageAdapter;
    private List<ImMessageBean> messageList = new ArrayList<>();

    private String userName = "";
    private String userId = "";
    private String headUrl = "";

    @Override
    protected void initViews() {
        setStatusBarHeight(StatusBarUtil.getStatusBarHeight(mContext));
        AppUtils.setStatusBarTextColor(true, getWindow());
        initClick(bd.tvSend, bd.header.headerBackImg);
        SoftHideKeyBoardUtil.assistActivity(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            userName = bundle.getString("userName", "");
            userId = bundle.getString("userId", "");
            headUrl = bundle.getString("headUrl", "");
        }
        bd.header.headerCenterTitle.setText(userName);
        bd.header.headerCenterTitle.setTextColor(ContextCompat.getColor(mContext, R.color.black));

        getLocalMessage();

        initRecycler();
        getMessage();
        refresh();
        bd.etContent.addTextChangedListener(new MTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.length() > 0) {
                    String content = s.toString();
                    if (content.contains("http://") || content.contains("https://")) {
                        bd.etContent.setText("");
                        if (content.contains("[") && content.contains("]")) {
                            String url = content.substring(content.indexOf("[") + 1, content.indexOf("]"));
                            if (content.contains(".jpg") || content.contains(".png") || content.contains(".jpeg") || content.contains(".gif")) {
                                showImgDialog(url);
                            } else {
                                new Thread(() -> {
                                    Document doc = null;//解析html字符串，获取document对象
                                    try {
                                        doc = Jsoup.connect(url).get();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    Elements body = doc.getElementsByTag("img");//获取body标签的元素
                                    Element element = body.get(0);//因为body是一个集合类型，所以需要取集合里的第一个元素
                                    showImgDialog(element.attr("src"));
                                }).start();
                            }
                        }
                    }
                    if (bd.tvSend.getVisibility() == View.GONE && !TextUtils.isEmpty(bd.etContent.getText().toString().trim())) {
                        bd.tvSelect.setVisibility(View.GONE);
                        bd.tvSend.setVisibility(View.VISIBLE);
                        bd.tvSend.clearAnimation();
                        ScaleAnimation scaleAnimation = new ScaleAnimation(0f, 1f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF
                                , 1f, Animation.RELATIVE_TO_SELF, 0.5f);
                        scaleAnimation.setDuration(200);
                        bd.tvSend.setAnimation(scaleAnimation);
                    }else {
                        bd.tvSelect.setVisibility(View.VISIBLE);
                        bd.tvSend.setVisibility(View.GONE);
                    }
                } else {
                    if (bd.tvSend.getVisibility() == View.VISIBLE) {
                        bd.tvSend.clearAnimation();
                        ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF
                                , 1f, Animation.RELATIVE_TO_SELF, 0.5f);
                        scaleAnimation.setDuration(200);
                        bd.tvSend.setAnimation(scaleAnimation);
                        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {
                                bd.tvSend.setVisibility(View.GONE);
                                bd.tvSelect.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                    }
                }
            }
        });
    }

    private LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, RecyclerView.VERTICAL, true);

    private void initRecycler() {
        messageAdapter = new ImMessageAdapter(messageList, mContext);
        bd.rvRecordList.setLayoutManager(linearLayoutManager);
        bd.rvRecordList.setHasFixedSize(true);
        bd.rvRecordList.setAdapter(messageAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v == bd.tvSend) {
            sendMessage(false);
        } else if (v == bd.header.headerBackImg) {
            finish();
        }
    }

    private void sendMessage(boolean isUrl) {
        sendMessage(isUrl, "");
    }

    private void sendMessage(boolean isUrl, String mg) {
        Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
        String text = bd.etContent.getText().toString().trim();
        if (isUrl) {
            text = mg;
        }
        TextMessage messageContent = TextMessage.obtain(text);
        Message message = Message.obtain(userId, conversationType, messageContent);
        //判断是否是url
        int flag = -1;
        HashMap<String, String> map = new HashMap<>();
        if (isUrl) {
            flag = ImConstant.ImMessage.MessageType.URL_IMAGE_OWN;
            map.put("flag", "image");
        } else {
            flag = ImConstant.ImMessage.MessageType.TEXT_OWN;
            map.put("flag", "text");
        }
        message.setCanIncludeExpansion(true);
        message.setExpansion(map);

        messageList.add(0, new ImMessageBean(text, MyUserInfo.getCurrentUser(MyUserInfo.class).getHeadUrl(),
                flag, true));
        messageAdapter.notifyItemInserted(0);
        bd.rvRecordList.smoothScrollToPosition(0);

        if (!isUrl) {
            saveLatestMessage(bd.etContent.getText().toString().trim());
            bd.etContent.setText("");
        } else {
            saveLatestMessage("[图片消息]");
        }
        RongIMClient.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() {

            @Override
            public void onAttached(Message message) {
                //触发时机：消息已存储数据库时
            }

            @Override
            public void onSuccess(Message message) {
                //触发时机：消息发送成功时
                Log.d(TAG, "onSuccess: 消息发送成功" + userId);
            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                //触发时机：消息发送失败时
                Log.d(TAG, "onError: 消息发送失败" + userId);
            }
        });
    }

    /**
     * 获取到发送过来的消息
     *
     * @return
     */
    private void getMessage() {
        RongIMClient.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean b, boolean b1) {
                TextMessage textMessage = (TextMessage) message.getContent();
                int flag;
                String value = message.getExpansion().get("flag");
                if (value != null && value.equals("image")) {
                    flag = ImConstant.ImMessage.MessageType.URL_IMAGE_OTHER;
                } else {//纯文字
                    flag = ImConstant.ImMessage.MessageType.TEXT_OTHER;
                }
                messageList.add(0, new ImMessageBean(textMessage.getContent(), headUrl, flag, false));
                messageAdapter.notifyItemInserted(0);
                bd.rvRecordList.smoothScrollToPosition(0);
                return false;
            }
        });
    }

    private void getLocalMessage() {
        Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;

        RongIMClient.getInstance().getHistoryMessages(conversationType, userId, oldestMessageId, pageSize,
                new RongIMClient.ResultCallback<List<Message>>() {
                    /**
                     * 成功时回调
                     * @param messages 获取的消息列表
                     */
                    @Override
                    public void onSuccess(List<Message> messages) {
                        if (messages != null && messages.size() > 0) {
                            int size = messageList.size();
                            MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
                            String ownHeadUrl = myUserInfo.getHeadUrl();
                            int flag;
                            for (int i = messages.size() - 1; i >= 0; i--) {
                                if (i == messages.size() - 1) {
                                    oldestMessageId = messages.get(i).getMessageId();
                                }
                                TextMessage textMessage = (TextMessage) messages.get(i).getContent();
                                String value = messages.get(i).getExpansion().get("flag");
                                if (userId.equals(messages.get(i).getSenderUserId())) {
                                    if (value != null && value.equals("image")) {
                                        flag = ImConstant.ImMessage.MessageType.URL_IMAGE_OTHER;
                                    } else {
                                        flag = ImConstant.ImMessage.MessageType.TEXT_OTHER;
                                    }
                                    messageList.add(size, new ImMessageBean(textMessage.getContent(), headUrl, flag, false));
                                } else {
                                    if (value != null && value.equals("image")) {
                                        flag = ImConstant.ImMessage.MessageType.URL_IMAGE_OWN;
                                    } else {
                                        flag = ImConstant.ImMessage.MessageType.TEXT_OWN;
                                    }
                                    messageList.add(size, new ImMessageBean(textMessage.getContent(), ownHeadUrl, flag, true));
                                }
                            }
                            messageAdapter.notifyItemRangeInserted(size, messages.size());
                        }
                    }

                    /**
                     * 错误时回调。
                     * @param e 错误码
                     */
                    @Override
                    public void onError(RongIMClient.ErrorCode e) {
                        showToast("获取失败");
                    }
                });
    }

    private int pageSize = 20;
    private int oldestMessageId = -1;

    private void refresh() {
        //下拉刷新
        bd.rvRecordList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (linearLayoutManager == null) {
                    linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                }
                if (linearLayoutManager == null) {
                    return;
                }
                totalCount = linearLayoutManager.getItemCount();
                visiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                if (totalCount == 0 || visiblePosition == 0) {
                    return;
                }
                if (is && dy < 0 && totalCount % visiblePosition == 4) {
                    is = false;
                    getLocalMessage();
                } else if (totalCount % visiblePosition != 4) {
                    is = true;
                }
            }
        });
    }

    private int totalCount = -1;
    private int visiblePosition = -1;
    private boolean is = false;

    /**
     * 将最近发送的一条消息保存到bmob
     */
    private void saveLatestMessage(String message) {
        MyUserInfo myUserInfo = MyUserInfo.getCurrentUser(MyUserInfo.class);
        String saveId = myUserInfo.getObjectId();
        String saveName = myUserInfo.getNickName();
        String saveHeadUrl = myUserInfo.getHeadUrl();
        BmobQuery<ConversationListBean> query1 = new BmobQuery<>();
        query1.addWhereEqualTo("saveId", saveId + "," + userId);
        BmobQuery<ConversationListBean> query2 = new BmobQuery<>();
        query2.addWhereEqualTo("saveId", userId + "," + saveId);
        List<BmobQuery<ConversationListBean>> list = new ArrayList<>();
        list.add(query1);
        list.add(query2);

        BmobQuery<ConversationListBean> query = new BmobQuery<>();
        query.or(list);
        query.findObjects(new FindListener<ConversationListBean>() {
            @Override
            public void done(List<ConversationListBean> list, BmobException e) {
                if (e == null) {
                    if (list != null && list.size() > 0) {
                        ConversationListBean bean = list.get(0);
                        bean.setLatestMessage(message);
                        bean.update(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    EventBus.getDefault().post(new ChangFresh(true));
                                } else {
                                }
                            }

                        });
                    } else {
                        add(message, saveId, saveName, saveHeadUrl);
                    }
                } else {
                    switch (e.getErrorCode()) {
                        case 101://添加数据
                            add(message, saveId, saveName, saveHeadUrl);
                            break;
                    }
                }
            }
        });
    }

    /**
     * 新增数据
     *
     * @param message
     * @param saveId
     */
    private void add(String message, String saveId, String saveName, String saveHeadUrl) {
        ConversationListBean bean = new ConversationListBean();
        bean.setSaveId(saveId + "," + userId);
        bean.setLatestMessage(message);
        bean.setaId(saveId);
        bean.setbId(userId);
        bean.setaHeadUrl(saveHeadUrl);
        bean.setbHeadUrl(headUrl);
        bean.setaName(saveName);
        bean.setbName(userName);
        bean.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    EventBus.getDefault().post(new ChangFresh(true));
                } else {
                }
            }
        });
    }

    private void showImgDialog(String url) {
        Log.d(TAG, "showImgDialog: " + url);
        CommonDialogFragment.newInstance().setLayout(DialogShowImgBinding.inflate(LayoutInflater.from(mContext), null, false))
                .setViewConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(DialogFragmentHolder holder, BaseDialogFragment dialogFragment, ViewBinding viewBinding) {
                        DialogShowImgBinding binding = (DialogShowImgBinding) viewBinding;
                        binding.tvTitle.setText("发送以下图片？");
                        GlideUtils.intoRadius(mContext, url, binding.ivImg, 4);
                        binding.tvRight.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                            sendMessage(true, url);
                        });
                        binding.tvLeft.setOnClickListener(v -> {
                            dialogFragment.dismiss();
                        });
                    }
                }).setAnimStyle(R.style.CenterDialogAnimation).setGravity(BaseDialogFragment.CENTER).setPercentSize(0.8f, 0f)
                .show(getSupportFragmentManager());
    }
}